//
//  SignedOperatedViewController.swift
//  mggz
//
//  Created by QinWei on 2018/5/2.
//  Copyright © 2018年 爱丽丝的梦境. All rights reserved.
//

import UIKit
import Moya
import AVFoundation
import ObjectMapper
class SignedOperatedViewController: BaseViewController {
    fileprivate var currentLat:Double? = 0
    fileprivate var currentLon:Double? = 0
    
    lazy var fenceList : [SignedDataModel] = [SignedDataModel]()
    lazy var signedPointList : [SignedDataModel] = [SignedDataModel]()
    fileprivate var isCanSubmit:Bool?
    fileprivate var isOnOvertimeWork:Bool? = false //是否加班中
    fileprivate var isOverWorkHours:Double?  //超出
    fileprivate var player:AVAudioPlayer?
    fileprivate var isRecordWork:Bool? = true
    fileprivate var signedInProjectState:Bool?
    fileprivate var signedOutProjectState:Bool?
    fileprivate var signedCoorArray = [CLLocationCoordinate2D]()
    fileprivate var mapView: BMKMapView = {
        let mapView = BMKMapView()
        //定位精度圈
        let param = BMKLocationViewDisplayParam()
        param.isAccuracyCircleShow = false //不显示精度圈
        param.locationViewOffsetX = 0
        param.isRotateAngleValid = false//定位图标朝向失效
        param.locationViewImgName = "sign_mine"//定位图标替换，需要将图片放置于mapapi.bundle/images目录
        mapView.updateLocationView(with: param)
        //地图配置要放在最后才会起效
        mapView.zoomLevel = 18//比例尺级别，越小越精确
        mapView.showsUserLocation = true
        //mapView.showMapScaleBar = true//显示比例尺
        
        return mapView
    }()
    
    var locationService = BMKLocationService()
    
    fileprivate var positionLabel: UILabel = {
        let label = UILabel()
        label.backgroundColor = UIColor.white
        label.numberOfLines = 2
        label.lineBreakMode = .byCharWrapping
        label.text = ""
        label.textColor = colorWith255RGB(102, g: 102, b: 102)
        label.font = wwFont_Regular(18)
        return label
    }()
    
    fileprivate var positionLabelIndicator: UIActivityIndicatorView = {
        let view = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.gray)
        return view
    }()
    
    fileprivate var recordButton: UIButton = {
        let button = UIButton()
        button.backgroundColor = UIColor.mg_noDataGray
        button.isEnabled = false
        button.titleLabel?.font = wwFont_Regular(20)
        button.layer.shadowColor = UIColor.black.cgColor
        button.layer.shadowOpacity = 0.2
        button.layer.shadowOffset = CGSize(width: 1, height: 1)
        return button
    }()
    
    //重新定位
    fileprivate var relocationButton: UIView = {
        let view = UIView()
        view.isUserInteractionEnabled = true
        view.backgroundColor = UIColor.white
        view.layer.cornerRadius = 18
        view.layer.shadowColor = UIColor.black.cgColor
        view.layer.shadowOpacity = 0.2
        view.layer.shadowOffset = CGSize(width: 0, height: 2)
        
        let imageView = UIImageView(image: UIImage.init(named: "定位")!.withRenderingMode(.alwaysTemplate))
        imageView.tintColor = UIColor.mg_blue
        imageView.contentMode = .scaleAspectFit
        
        let label = UILabel()
        label.text = "重新定位"
        label.textColor = UIColor.black
        label.font = wwFont_Regular(16)
        label.textColor = colorWith255RGB(102, g: 102, b: 102)
        
        view.addSubview(imageView)
        imageView.snp.makeConstraints({ (make) in
            make.centerY.equalTo(view)
            make.left.equalTo(view).offset(15)
            make.width.height.equalTo(23)
        })
        
        view.addSubview(label)
        label.snp.makeConstraints({ (make) in
            make.left.equalTo(imageView.snp.right).offset(5)
            make.top.bottom.equalTo(imageView)
            make.right.equalTo(view).offset(3)
        })
        
        return view
    }()
    
    var inRange = false {//判断是否达到签到距离，默认没达到
        willSet {
            self.inRange = newValue
            self.positionLabelIndicator.stopAnimating()
            if newValue {
                self.positionLabel.text = "    " + "我的位置（在签到范围内）"
                self.recordButton.backgroundColor = UIColor.mg_blue
                self.recordButton.isEnabled = true
            }
            else {
                self.positionLabel.text = "    " + "我的位置（不在签到范围内）"
                self.recordButton.backgroundColor = UIColor.mg_noDataGray
                self.recordButton.isEnabled = false
            }
        }
    }
    
    /***传入数据变量***/
    var signedType:SignedType? //签入签出
    var projectModel:ProjectModel? //当前项目
    
    //签到方式
    
    var signOutAlert2:TWLAlertView?
    var signOutAlert3:TWLAlertView?
    
    fileprivate
    var systemWorkPoints:String?
    
    /***本地数据变量***/
    var recordPolicy: RecordPolicy?//签到策略
    
    var recordOperationHandler:(() -> Void)?
    var audioPlayer:((Int,Bool) -> Void)?
    fileprivate var selectPoint:String?
    override func viewDidLoad() {
        super.viewDidLoad()
        self.getSystemWorkPoints()
        self.isCanSubmit = false
        self.selectPoint = "0.5"
        self.view.backgroundColor = UIColor.mg_backgroundGray
        self.getSwitchProjectState()
        self.getLocationAuthorizationState()
        self.setupSignedType()
        self.getData()
        self.setupViews()
        self.showLoadingView()
        self.positionLabelIndicator.startAnimating()
    }
    
    //签出及签入时，项目的状态
    fileprivate func getSwitchProjectState(){
        guard let demandBaseMigrantWorkerID = self.projectModel?.demandBaseMigrantWorkerID else {
            return
        }
    CommonUsed.checkOtherProjectSignedIn(demandBaseMigrantWorkerID: demandBaseMigrantWorkerID) { (state) in
            self.signedInProjectState = state
        }
//        CommonUsed.checkOtherProjectSignedOut(demandBaseMigrantWorkerID: demandBaseMigrantWorkerID) { (state) in
//            self.signedOutProjectState = state
//        }
    }
    
    fileprivate func setupSignedType(){
        switch self.signedType! {
        case .signedIn:
            self.title = "签入操作"
        case .signedOut:
            self.title = "签出操作"
        case .notInRange:
            self.title = "不在签到范围内"
        }
    }
    //定位开启的状态判断
    fileprivate func getLocationAuthorizationState(){
        if CLLocationManager.authorizationStatus() == .denied{
            let alert = UIAlertController(title: "打开[定位服务]来允许太公民工获取您的位置", message: "请在系统设置中开启定位服务(设置>隐私>定位服务>开启)", preferredStyle: .alert)
            let refuseApp = UIAlertAction(title: "取消", style: .cancel, handler: { (action) in
                
            })
            let gotoAppstore = UIAlertAction(title: "设置", style: .default, handler: { (action) in
                if let appSettings = NSURL(string: UIApplicationOpenSettingsURLString) {
                    
                    UIApplication.shared.openURL(appSettings as URL)
                }
            })
            alert.addAction(gotoAppstore)
            alert.addAction(refuseApp)
            self.present(alert, animated: true, completion: {
                
            })
        }
    }
    //获取系统的工数的情况
    fileprivate func getSystemWorkPoints(){
        guard let accountId = WWUser.sharedInstance.accountId else{
            return
        }
        guard let demandBaseMigrantWorkerID = self.projectModel?.demandBaseMigrantWorkerID else{
            
            return
        }
    LCAPiSubManager.request(.GetMigrantWorkerSignedDays(demandBaseMigrantWorkerID: demandBaseMigrantWorkerID, AccountId: accountId)) { (result) in
            if case let .success(response) = result {
                guard  let jsonString :NSDictionary = try?response.mapJSON() as! NSDictionary else{
                    return
                }
               
                guard (jsonString["State"]) as! String == "OK" else{
                    return
                }
                
                guard let resultDic:NSDictionary = jsonString["Result"] as? NSDictionary else{
                    return
                }
                if let isSubmit : Bool = resultDic["IsSubmit"] as? Bool{
                    self.isCanSubmit = isSubmit
                }
                if let isOnOvertime : Bool = resultDic["IsOverTimeWork"] as? Bool{
                    self.isOnOvertimeWork = isOnOvertime
                }
                if let overWorkHours : Double = resultDic["OverWorkHours"] as? Double{
                    self.isOverWorkHours = overWorkHours
                }
                
                if let systemWorkDay2 : Float = resultDic["WorkDays"] as? Float{
                    self.systemWorkPoints = String(systemWorkDay2)
                   
                    self.selectPoint = String(systemWorkDay2)
                    
                }
            }
        }
    }
    
    override func viewWillAppear(_ animated: Bool) {
        mapView.viewWillAppear()
        self.mapView.delegate = self
        locationService.delegate = self
        
        self.getData()
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        locationService.delegate = nil
        mapView.delegate = nil
        mapView.viewWillDisappear()
    }
    
    func setupViews() {
        self.view.addSubview(self.mapView)
        self.mapView.snp.makeConstraints { (make) in
            make.left.right.equalTo(self.view)
            make.top.equalTo(self.view).offset(64)
            make.height.equalTo(self.view.bounds.height * 0.56)
        }
        
        let relocationTap = UITapGestureRecognizer(target: self, action: #selector(doRelocationAction))
        //relocationTap.cancelsTouchesInView = false
        //relocationTap.delaysTouchesEnded = false
        self.relocationButton.addGestureRecognizer(relocationTap)
        //        self.relocationButton.addGestureRecognizer(UITapGestureRecognizer.init(target: self, action: #selector(doRelocationAction)))
        
        self.mapView.addSubview(self.relocationButton)
        self.relocationButton.snp.makeConstraints { (make) in
            make.bottom.equalTo(self.mapView).offset(-10)
            make.left.equalTo(self.mapView).offset(20)
            make.size.equalTo(CGSize.init(width: 120, height: 35))
        }
        
        self.view.addSubview(self.positionLabel)
        self.positionLabel.snp.makeConstraints { (make) in
            make.left.right.equalTo(self.view)
            make.height.equalTo(50)
            make.top.equalTo(self.mapView.snp.bottom)
        }
        
        self.view.addSubview(self.positionLabelIndicator)
        self.positionLabelIndicator.snp.makeConstraints { (make) in
            make.centerY.equalTo(self.positionLabel)
            make.right.equalTo(self.mapView)
        }
        
        let bottomPanel = UIView()
        self.view.addSubview(bottomPanel)
        bottomPanel.snp.makeConstraints { (make) in
            make.left.right.bottom.equalTo(self.view)
            make.top.equalTo(self.positionLabel.snp.bottom)
        }
        
        switch self.signedType! {
        case .signedIn:
            self.recordButton.setTitle("签入操作", for: .normal)
        case .signedOut:
            self.recordButton.setTitle("签出操作", for: .normal)
        case .notInRange:
            self.recordButton.setTitle("不在签到范围内", for: .normal)
        }
        
        self.recordButton.addTarget(self, action: #selector(alertRecordAction), for: .touchUpInside)
        bottomPanel.addSubview(self.recordButton)
        self.recordButton.snp.makeConstraints { (make) in
            make.left.equalTo(self.view).offset(20)
            make.right.equalTo(self.view).offset(-20)
            make.height.equalTo(50)
            make.centerY.equalTo(bottomPanel)
        }
        let signedRemindView = SignedPromptView()
        signedRemindView.frame = CGRect(x: SCREEN_WIDTH-79, y: 70, width: 69, height: 65)
        self.view.addSubview(signedRemindView)
        self.view.bringSubview(toFront: signedRemindView)
    }
    
    @objc func doRelocationAction() {
        //定位跟随模式
        self.mapView.showsUserLocation = false;
        self.mapView.userTrackingMode = BMKUserTrackingModeFollow
        self.mapView.showsUserLocation = true;
        self.mapView.zoomLevel = 18
    }
    
    @objc func alertRecordAction() {
        
        if self.signedType == SignedType.signedOut {
//            if self.signedOutProjectState == true{
//                CommonUsed.commonAlertStytle("由于您之前没有签出就在别的工地考勤，所以此次签出将不记工！", rightTitle: "签出", leftTitle: "取消", controller: self) {
//                    self.doRecordActon()
//                }
//            }else{
                self.singedOutMainLogic()
           // }
        }
        else if self.signedType == .signedIn {
            if self.signedInProjectState == true{
                CommonUsed.commonAlertStytle("您还有未签出的项目，强制在新项目签到，之前的项目将视作放弃记工！", rightTitle: "强制签入", leftTitle: "取消", controller: self) {
                    self.doRecordActon()
                }
            }else{
                self.doRecordActon()
            }
        }
        
    }
    //签出的主体逻辑
    fileprivate func singedOutMainLogic(){
        self.getSignedHalfHourData { (value1,value2) in
            if value1 == 0{
                self.halfHourAlertView(1, message: value2!)
                self.isRecordWork = false
            }else if value1 == 1{
                self.halfHourAlertView(2, message: value2!)
                self.isRecordWork = false
            }else if value1 == 2{
                self.halfHourAlertView(3, message: value2!)
                self.isRecordWork = true
            }else if value1 == 3{
                self.halfHourAlertView(4, message: value2!)
                self.isRecordWork = false
            }else if value1 == 4{
                self.halfHourAlertView(5, message: value2!)
                self.isRecordWork = false
            }else{
                self.makeSignedOutActions()
                self.isRecordWork = true
            }
        }
    }
    fileprivate func halfHourAlertView(_ sort:Int,message:String){
        self.signOutAlert2 = TWLAlertView.init(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: SCREEN_HEIGHT))
        let advanceSureView = LoginOutSignView(frame: CGRect(x: 0, y: 0, width: 280, height: 175))
        advanceSureView.cancelButton.setTitleColor(UIColor.init(red: 0.97, green: 0.43, blue: 0.38, alpha: 1), for: .normal)
        advanceSureView.loginButton.setTitleColor(UIColor.init(red: 0.40, green: 0.40, blue: 0.40, alpha: 1), for: .normal)
        advanceSureView.loginButton.setTitle("取消", for: .normal)
        advanceSureView.headerIcon.image = UIImage(named: "retn_bankcon")
        
        if sort == 1{
            advanceSureView.messageLabel.text = message
            advanceSureView.cancelButton.setTitle("强制签出", for: .normal)
            advanceSureView.cancelButton.addTarget(self, action: #selector(self.lessThanHalfHourAction), for: .touchUpInside)
        }else if sort == 2 || sort == 4 || sort==5{
            advanceSureView.messageLabel.text = message
            advanceSureView.cancelButton.setTitle("签出", for: .normal)
            advanceSureView.cancelButton.addTarget(self, action: #selector(self.lessThanHalfHourAction), for: .touchUpInside)
        }else if sort == 3{
            advanceSureView.messageLabel.text = "此次考勤时间还不足半个小时，您确定要签出吗？"
            advanceSureView.cancelButton.setTitle("签出", for: .normal)
            advanceSureView.cancelButton.addTarget(self, action: #selector(self.signStageActionClick), for: .touchUpInside)
        }
        advanceSureView.loginButton.addTarget(self, action: #selector(signViewCancel), for: .touchUpInside)
        
      self.signOutAlert2?.initWithCustomView(advanceSureView, frame: CGRect(x: 0, y: 0, width: 280, height: 175))
        let keyWindow = UIApplication.shared.keyWindow
        keyWindow?.addSubview(self.signOutAlert2!)
    }
    @objc fileprivate func lessThanHalfHourAction(){
        self.signOutAlert2?.cancleView()
        self.doRecordActon()
    }
    @objc fileprivate func signStageActionClick(){
        self.signOutAlert2?.cancleView()
        self.makeSignedOutActions()
    }
    @objc fileprivate func signViewCancel(){
        self.signOutAlert2?.cancleView()
    }
    fileprivate func makeSignedOutActions(){
        if self.isOnOvertimeWork == false{
            
            self.normalCourseAction()
        }else{
            if self.isOverWorkHours == 0.0{
                self.doRecordActon()
            }else{
                self.normalCourseAction()
                
            }
        }
    }
    
    //加班条件判断之后的正常流程
    fileprivate func normalCourseAction(){
        
        if self.projectModel?.workDayType == 2{
            let alertController = ETSimpleAlertController.init("您确定要离场吗？") {[unowned self] in
                self.doRecordActon()
            }
            self.present(alertController, animated: true, completion: nil)
            
        }else if self.projectModel?.workDayType == 0{
            if self.systemWorkPoints == "0.0"{
                self.doRecordActon()
            }else{
                self.setupRecordWorkpointsViewAlert3()
                
            }
        }else{
            if self.isCanSubmit == true{
                if self.systemWorkPoints == "0.0"{
                    self.doRecordActon()
                }else{
                    self.setupRecordWorkpointsViewAlert3()
                }
            }else{
                self.setupSignOutWorkPointsAlert()
            }
        }
        
    }
    fileprivate func getSignedHalfHourData(_ completion:@escaping (Int?,String?) -> Void){
        guard let accountId = WWUser.sharedInstance.accountId else{
            return
        }
        
        guard let demandBaseMigrantWorkerID = self.projectModel?.demandBaseMigrantWorkerID else{
            return
        }
    LCAPiSubManager.request(.GetSignedHalfHourData(demandBaseMigrantWorkerID: demandBaseMigrantWorkerID, AccountId: accountId)) { (result) in
            if case let .success(response) = result {
                guard  let jsonString :NSDictionary = try?response.mapJSON() as! NSDictionary else{
                    return
                }
               
                guard (jsonString["State"]) as! String == "OK" else{
                    completion(100, "正常")
                    return
                }
                
                let result = jsonString["Result"] as? Int
                let message = jsonString["Msg"] as? String
                completion(result, message)
            }
        }
    }
    fileprivate func setupSignOutWorkPointsAlert(){
        self.signOutAlert2 = TWLAlertView.init(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: SCREEN_HEIGHT))
        let custom : RecordWorkpointsView4 = RecordWorkpointsView4.init(frame: CGRect(x: 0, y: 0, width: 240, height: 285))
        custom.cancelButton.addTarget(self, action: #selector(customCancelClick), for: .touchUpInside)
        custom.recordPoints.addTarget(self, action: #selector(recordPointsClick), for: .touchUpInside)
        custom.systemPoints = self.selectPoint
        custom.selectedPoints = {(value) in
            self.selectPoint = value
        }
        let recordArray = ["0.5","0.75","1.0","1.5","2.0","3.0"]
        
        for (index,value) in recordArray.enumerated(){
            if self.systemWorkPoints == value{
                custom.pickView.selectRow(index, inComponent: 0, animated: true)
            }
        }
        self.signOutAlert2?.initWithCustomView(custom, frame: CGRect(x: 0, y: 0, width: 240, height: 285))
        
        let keyWindow = UIApplication.shared.keyWindow
        keyWindow?.addSubview(self.signOutAlert2!)
    }
    @objc fileprivate func customCancelClick(){
        self.signOutAlert2?.cancleView()
        self.selectPoint = self.systemWorkPoints
    }
    @objc fileprivate func recordPointsClick(){
        self.signOutAlert2?.cancleView()
        if self.selectPoint  != self.systemWorkPoints{
            let alertController = ETSimpleAlertController.init("你对工时进行了调整，需要上级批准后方可生效，并且一天只能调整一次。\n确定要调整吗？") {[unowned self] in
                self.doRecordActon()
            }
            self.present(alertController, animated: true, completion: nil)
        }else{
            self.doRecordActon()
        }
    }
    //提交工时数据
    fileprivate func recordSetMigrantWorkerSignedDays(){
        guard let accountId = WWUser.sharedInstance.accountId else{
            return
        }
        guard (self.systemWorkPoints != nil) else{
            return
        }
        guard (self.selectPoint != nil) else{
            return
        }
        guard let demandBaseMigrantWorkerID = self.projectModel?.demandBaseMigrantWorkerID else{
            return
        }
        LCAPiSubManager.request(.SetMigrantWorkerSignedDays(demandBaseMigrantWorkerID: demandBaseMigrantWorkerID, signedWorkDays: self.systemWorkPoints! as NSString, workDays: self.selectPoint!, AccountId: accountId)) { (result) in
            if case let .success(response) = result {
                guard  let jsonString :NSDictionary = try?response.mapJSON() as! NSDictionary else{
                    return
                }
                guard (jsonString["State"]) as! String == "OK" else{
                    return
                }
                
                WWSuccess("签出成功")
        self.navigationController?.popViewController(animated: true)
            }
        }
        
    }
    func doRecordActon() {
        if self.signedType == .signedOut{
            guard let demandBaseMigrantWorkerID = self.projectModel?.demandBaseMigrantWorkerID else {
                return
            }
            
            CommonUsed.uploadTrajectoryData(demandBaseMigrantWorkerID, isException: false, longitude: "\(self.currentLon!)", latitude: "\(self.currentLat!)", userAdress: TrackUploadService.sharedInstance.userAdress!) { (state) in
                self.doRecordIndeedActon()
            }
        }else{
       
            self.doRecordIndeedActon()
        
        }
    }
    fileprivate func doRecordIndeedActon(){
        guard self.signedType != SignedType.notInRange else{
            return
        }
        guard ((self.projectModel?.workDayType) != nil) else {
            return
        }
        WWProgressHUD.showWithStatus("")
        
        var guid: String?
        
        let _dispatchGroup = DispatchGroup()
        
        _dispatchGroup.enter()
        UserModel.getGuid { (response) in
            if response.success {
                guid = response.value
            }
            else{
                WWError(response.message)
            }
            _dispatchGroup.leave()
        }
        
        _dispatchGroup.notify(queue: DispatchQueue.main) {
            guard guid != nil else {
                WWError("guid是空的")
                return
            }
            RecordModel.record(guid:guid!,demandBaseMigrantWorkerId: self.projectModel!.demandBaseMigrantWorkerID!, signedType: self.signedType!){(response) in
                if response.success {
                    
                    if let handler = self.recordOperationHandler {
                        handler()
                    }
                    
                    if self.projectModel?.workDayType == 2 || self.projectModel?.workDayType == 0 || self.signedType == .signedIn {
                        WWProgressHUD.dismiss()
                        
                        if self.signedType == .signedIn{
                            WWSuccess("签入成功")
                            guard let demandBaseMigrantWorkerID = self.projectModel?.demandBaseMigrantWorkerID else {
                                return
                            }
                            
                            CommonUsed.uploadTrajectoryData(demandBaseMigrantWorkerID, isException: false, longitude: "\(self.currentLon!)", latitude: "\(self.currentLat!)", userAdress: TrackUploadService.sharedInstance.userAdress!) { (state) in
                                //self.doRecordIndeedActon()
                                self.audioPlayer!(Int(1), self.isRecordWork!)
                                 self.navigationController?.popViewController(animated: true)
                            }
                            
                            
                        }else{
                            WWSuccess("签出成功")
                            self.audioPlayer!(Int(2), self.isRecordWork!)
                             self.navigationController?.popViewController(animated: true)
                            
                        }
                        
                       
                        
                    }else{
                        
                        self.recordSetMigrantWorkerSignedDays()
                    }
                }
                else {
                    WWError(response.message)
                }
            }
        }
    }
    fileprivate func setupRecordWorkpointsViewAlert3(){
        self.signOutAlert3 = TWLAlertView.init(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: SCREEN_HEIGHT))
        let custom : RecordWorkpointsView3 = RecordWorkpointsView3.init(frame: CGRect(x: 0, y: 0, width: 300, height: 145))
        if self.isOnOvertimeWork == true{
            custom.titleLabel.text = "根据考勤时间与加班时间计算"
            custom.recordLabel.text = "合计"
        }else{
            custom.titleLabel.text = "根据考勤时间自动计算"
            custom.recordLabel.text = "计"
        }
        custom.cancelButton.addTarget(self, action: #selector(alert3CancelClick), for: .touchUpInside)
        custom.makeSureButton.addTarget(self, action: #selector(alert3MakeSureButtonClick), for: .touchUpInside)
        if (systemWorkPoints != nil){
            custom.workPoints.text = self.systemWorkPoints
        }
        self.signOutAlert3?.initWithCustomView(custom, frame: CGRect(x: 0, y: 0, width: 300, height: 145))
        let keyWindow = UIApplication.shared.keyWindow
        keyWindow?.addSubview(self.signOutAlert3!)
    }
    
    @objc fileprivate func alert3CancelClick(){
        
        self.signOutAlert3?.cancleView()
        
    }
    
    @objc fileprivate func alert3MakeSureButtonClick(){
        self.signOutAlert3?.cancleView()
        self.doRecordActon()
    }
    
    //配置目的地
    func configDestination(_ model: RecordPolicy) {
        self.fenceList = Mapper<SignedDataModel>().mapArray(JSONObject: model.electricFenceList)!
        self.signedPointList = Mapper<SignedDataModel>().mapArray(JSONObject: model.signedPointList)!
        var fenceCoorArr = [CLLocationCoordinate2D]()
        for (_,value) in self.fenceList.enumerated() {
            if let lat = value.Latitude, let lon = value.Longitude {
                if let doubuleLat = Double(lat), let doubleLon = Double(lon) {
                  var coor = CLLocationCoordinate2D()
                  coor.latitude = doubuleLat
                  coor.longitude = doubleLon
                  fenceCoorArr.append(coor)
                }
            }
        }
        let polygon2 = BMKPolygon(coordinates: &fenceCoorArr, count: UInt(fenceCoorArr.count))
        self.mapView.add(polygon2)
        
        for (_,value2) in self.signedPointList.enumerated() {
            if let lat = value2.Latitude, let lon = value2.Longitude {
                if let doubuleLat = Double(lat), let doubleLon = Double(lon) {
                    let annotation = BMKPointAnnotation()
                    var coor = CLLocationCoordinate2D()
                    coor.latitude = doubuleLat
                    coor.longitude = doubleLon
                    self.signedCoorArray.append(coor)
                    annotation.coordinate = coor
                    self.mapView.addAnnotation(annotation)
                    let aRadius = model.signedRange ?? "100"
                    let circlePoint = BMKCircle(center: coor, radius: Double(aRadius)!)
                    self.mapView.add(circlePoint)
                }
            }
        }
    }
    //获取签到策略
    func getData() {
        guard self.projectModel != nil , let marketSupplyBaseID = self.projectModel!.marketSupplyBaseID else{
            WWError("当前项目是空的！")
            return
        }
        
        RecordPolicy.getRecordPolicy(aID: marketSupplyBaseID, completionHandler: { (response) in
            if response.success {
                self.recordPolicy = response.value
                
                self.configDestination(response.value!)
            }
            else {
                WWError(response.message)
            }
            
            self.locationService.stopUserLocationService()
            self.locationService.startUserLocationService()
            self.mapView.userTrackingMode = BMKUserTrackingModeFollow
            
            self.hideLoadingView()
        })
        
    }
    deinit {
        
    }
}
extension SignedOperatedViewController:BMKMapViewDelegate, BMKLocationServiceDelegate,AVAudioPlayerDelegate {
    
    func mapView(_ mapView: BMKMapView!, viewFor overlay: BMKOverlay!) -> BMKOverlayView! {
        if (overlay as? BMKCircle) != nil {
            let circleView = BMKCircleView(overlay: overlay)
            circleView?.fillColor = colorWith255RGBA(16, g: 142, b: 233, a: 0.1)
            circleView?.strokeColor = colorWith255RGBA(136, g: 191, b: 255, a: 1)
            circleView?.lineWidth = 0.5
            
            return circleView
        }
        if (overlay as? BMKPolygon) != nil {
            let polygonView = BMKPolygonView(overlay: overlay)
            polygonView?.strokeColor = UIColor(red: 0, green: 0, blue: 0.5, alpha: 1)
            polygonView?.fillColor = UIColor(red: 0.98, green: 0.63, blue: 0.07, alpha: 0.1)
            polygonView?.lineWidth = 1
            polygonView?.lineDash = true
            return polygonView
        }
        return UIView() as! BMKOverlayView
    }
    
    func mapView(_ mapView: BMKMapView!, viewFor annotation: BMKAnnotation!) -> BMKAnnotationView! {
        let AnnotationViewID = "renameMark"
        var annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: AnnotationViewID) as BMKAnnotationView?
        if annotationView == nil {
            annotationView = BMKAnnotationView(annotation: annotation, reuseIdentifier: AnnotationViewID)
          annotationView?.image = UIImage(named: "kaoqin")
          annotationView?.frame = CGRect(x: 0, y: 0, width: 3, height: 3)//大头针大小，根据图片宽高比等比配置
          annotationView?.annotation = annotation
            return annotationView
        }
        return nil
    }
    // 用户位置更新后回调
    func didUpdate(_ userLocation: BMKUserLocation!) {
        self.mapView.updateLocationData(userLocation)
        
        if !self.positionLabelIndicator.isAnimating {
            self.positionLabelIndicator.startAnimating()
        }
        
        let currentLocation = userLocation.location.coordinate
        self.currentLat = currentLocation.latitude
        self.currentLon = currentLocation.longitude
        guard let model = self.recordPolicy else {
            return
        }
        var signF:Int? = 0
        if self.signedCoorArray.count > 0{
            for (_,value) in self.signedCoorArray.enumerated(){
                if BMKCircleContainsCoordinate(currentLocation, value, Double(model.signedRange!)!) == true{
                    signF = signF!+1
                }
            }
            if signF == 0{
                self.inRange = false
            }else{
              self.inRange = true
            }
        }
    }
}









